package com.yiper.controller;

import com.yiper.entity.Permission;
import com.yiper.security.ShiroFilterChainService;
import com.yiper.service.PermissionService;
import com.yiper.util.ResponseUtil;
import com.yiper.vo.ResponseVo;
import com.yiper.vo.SystemConst;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    private static final Logger logger = LoggerFactory.getLogger(PermissionController.class);
    /**1:全部资源，2：菜单资源*/
    private static final String[] MENU_FLAG ={"1","2"};
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ShiroFilterChainService shiroFilterChainService;

    /**
     * <p class="detail">
     * 功能:初始化资源列表
     * </p>
     *
     * @param flag :
     * @return list
     * @author BaoWeiwei
     * @date 2018.07.24 17:40:16
     */
    @PostMapping("/list")
    @ResponseBody
    public List<Permission> loadPermissions(String flag){
        List<Permission> permissionList = new ArrayList<Permission>();
        if(StringUtils.isBlank(flag) || MENU_FLAG[0].equals(flag)){
            permissionList = permissionService.selectAll(SystemConst.DATA_VALID);
        }else if(MENU_FLAG[1].equals(flag)){
            permissionList = permissionService.selectAllMenuName(SystemConst.DATA_VALID);
        }
        return permissionList;
    }

    /**
     * <p class="detail">
     * 功能:资源详情
     * </p>
     *
     * @param model        :
     * @param permissionId :
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.24 21:39:50
     */
    @GetMapping("/edit/{permissionId}")
    public String detail(Model model, @PathVariable("permissionId") String permissionId) {
        Permission permission = permissionService.findByPermissionId(permissionId);
        if(null != permission){
            if(permission.getParentId().equals(SystemConst.TOP_MENU_ID)){
                model.addAttribute("parentName", SystemConst.TOP_MENU_NAME);
            }else{
                Permission parent = permissionService.findByPermissionId(permission.getParentId());
                model.addAttribute("parentName", parent.getName());
            }
        }
        model.addAttribute("permission", permission);
        return "permission/detail";
    }

    /**
     * <p class="detail">
     * 功能:修改资源
     * </p>
     *
     * @param permission :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 22:46:03
     */
    @ResponseBody
    @PostMapping("/edit")
    public ResponseVo editPermission(Permission permission){
        int a = permissionService.updateByPermissionId(permission);
        if (a > 0) {
            shiroFilterChainService.reloadPermission();
            return ResponseUtil.success("编辑权限成功");
        } else {
            return ResponseUtil.error("编辑权限失败");
        }
    }

    /**
     * <p class="detail">
     * 功能:删除权限
     * </p>
     *
     * @param permissionId :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 22:46:25
     */
    @ResponseBody
    @PostMapping("/delete")
    public ResponseVo deletePermission(String permissionId){
        try {
            int subPermsByPermissionIdCount = permissionService.selectSubPermsByPermissionId(permissionId);
            if(subPermsByPermissionIdCount > 0){
                return ResponseUtil.error("该资源存在下级资源，无法删除！");
            }
            int a = permissionService.updateStatus(permissionId,SystemConst.DATA_DELETED);
            if (a > 0) {
                shiroFilterChainService.reloadPermission();
                return ResponseUtil.success("删除资源成功");
            } else {
                return ResponseUtil.error("删除资源失败");
            }
        } catch (Exception e) {
            logger.error(String.format("PermissionController.deletePermission%s", e));
            throw e;
        }
    }

    /**
     * <p class="detail">
     * 功能:新增资源
     * </p>
     *
     * @param permission :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 23:32:04
     */
    @ResponseBody
    @PostMapping("/add")
    public ResponseVo addPermission(Permission permission){
        // 判断新加的资源是否和当前父节点下的资源名称重复，如果重复，不允许添加
        List<Permission> permissions = permissionService.selectAllPermission(permission.getParentId());
        for(Permission perm : permissions){
            if(perm.getName().equals(permission.getName())){
                return ResponseUtil.error("该上级资源下有同名资源，请重新添加");
            }
        }
        try {
            int a = permissionService.insert(permission);
            if (a > 0) {
                shiroFilterChainService.reloadPermission();
                return ResponseUtil.success("添加权限成功");
            } else {
                return ResponseUtil.error("添加权限失败");
            }
        } catch (Exception e) {
            logger.error(String.format("PermissionController.addPermission%s", e));
            throw e;
        }
    }


}
